﻿using MediatR;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Dtos;

namespace Enterprise_Set.API.Application.Commands.Week3.WHAllot_CRUD
{
    /// <summary>
    /// 显示仓库调用表数据
    /// </summary>
    public class ShowAllotDataHander : IRequestHandler<ShowAllotDataCommand, Result>
    {
        private readonly IBaseRepository<dynamic> dynamicRepository;

        public ShowAllotDataHander(IBaseRepository<dynamic> dynamicRepository)
        {
            this.dynamicRepository = dynamicRepository;
        }

        public async Task<Result> Handle(ShowAllotDataCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCodes.Search };
            //获取仓库表数据
            var Getsql = "select * from Warehouse;";
            var GetData = dynamicRepository.GetAll(Getsql);
            //获取仓库调拨表数据
            var sql = "select * from WHAllot;";
            var Data = dynamicRepository.GetAll(sql);
            List<ShowAllotDataDTO> AllotDataList = new List<ShowAllotDataDTO>();
            if (GetData != null)
            {
                foreach (var item in Data)
                {
                    ShowAllotDataDTO showAllotDataDTO = new ShowAllotDataDTO()
                    {
                        WHAllotId = item.WHAllotId,
                        WHAllotNum = item.WHAllotNum,
                        WHAllotTime = item.WHAllotTime,
                        WarehouseSourceName = "",
                        WarehouseSourceAddr = item.WarehouseSourceAddr,
                        WarehouseGoalName = "",
                        WarehouseGoalAddr = item.WarehouseGoalAddr,
                        WHAllotState = Convert.ToInt32(item.WHAllotState),
                        WHAllotRemark = item.WHAllotRemark,
                        WHAllotCreateName = item.WHAllotCreateName,
                        WHAllotCreateBranch = item.WHAllotCreateBranch,
                    };
                    foreach (var item2 in GetData)
                    {
                        if (item.WarehouseSourceid == item2.WarehouseId)
                        {
                            showAllotDataDTO.WarehouseSourceName = item2.WarehouseName;
                        }
                        if (item.WarehouseGoalId == item2.WarehouseId)
                        {

                            showAllotDataDTO.WarehouseGoalName=item2.WarehouseName;  
                        }
                    }
                    AllotDataList.Add(showAllotDataDTO);
                }
            }

            if (Data != null)
            {
                result.Code = (int)CommonErrorCodes.Success;
                result.Data = AllotDataList;
                return result;
            }
            else
            {
                return result;
            }
        }
    }
}
